from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from app.models import FMUser


class UserCreationForm(forms.ModelForm):
    """
    A form for creating new user. Includes all the required
    fields, plus a repeated password.
    """
    password1 = forms.CharField(label='密码', widget=forms.PasswordInput)
    password2 = forms.CharField(label='重复密码', widget=forms.PasswordInput)

    class Meta:
        module = FMUser
        fields = ['username', 'realname', 'identity', 'email', 'date_of_birth']

    def clean_password2(self):
        # Check that the two password entries matc
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError('两次密码不相同')
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(UserCreationForm, self).save(commit=True)
        user.set_password(self.cleaned_data['password1'])
        if commit:
            user.save()
        return user


class UserChangeForm(forms.ModelForm):
    '''
    A form for updating users. Includes all the fields on the user,
    but replaces the password field with admin's password has display field.
    '''
    password = ReadOnlyPasswordHashField()

    class Meta():
        model = FMUser
        fields = ('username', 'realname', 'identity', 'email', 'password', 'date_of_birth', 'is_active', 'is_superuser')

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial['password']
